// pages/connect/bedside/bedside.js
const app = getApp()
const utils = require('../../../utils/util')
const api = require("../../../utils/api")
const bluetoothUtils = require("../../../utils/bluetoothUtils")
Page({

    /**
     * 页面的初始数据
     */
    data: {
        stage: 1, //连接床阶段，1-选边，2-连接中，3-结果显示
        selectFlag: false,
        bedside: 1, //床边 1-左，0-右，2-一人睡双床
        onlySideFlag: false, //是否只剩单边
        value: 0,
        bedinfo: {},
        errFlag: true,
        nextpath: '',
        failedFlag: false,
        hasbind: false,
    },
    //床边情况
    bedsituation: function (params) {
        const arr = [{
                name: '左侧空位',
                left: false,
                right: true,
                side: 1,
                only: true
            },
            {
                name: '右侧空位',
                left: true,
                right: false,
                side: 0,
                only: true
            },
            {
                name: '两侧空位',
                left: false,
                right: false,
                side: 2,
                only: false
            },
            {
                name: '无空位',
                left: true,
                right: true,
                side: 2,
                only: false
            },
        ]
        arr.filter(item => {
            if (item.left == params.left_select_flag && item.right == params.right_select_flag) {
                this.setData({
                    bedside: item.side,
                    onlySideFlag: item.only
                })
            }
        })
    },
    oneManSleep: function () {
        if (!this.data.onlySideFlag) {
            this.setData({
                selectFlag: !this.data.selectFlag,
                bedside: 2
            })
            // if (this.data.selectFlag == false) {
            //     this.setData({
            //         bedside: 1
            //     })
            // } else {
            //     this.setData({
            //         bedside: 2
            //     })
            // }
        }

    },
    bedSideSelect: function (e) {
        if (!this.data.onlySideFlag) {
            // if (this.data.selectFlag == false) {
            let temp = e.target.dataset.index
            console.log(temp, e)
            if (temp) {
                if (temp == 1) {
                    this.setData({
                        bedside: 1
                    })
                } else {
                    this.setData({
                        bedside: 0
                    })
                }
            }

            // switch (this.data.bedside) {
            //     case 0:
            //         this.setData({
            //             bedside: 1
            //         });
            //         break;
            //     case 1:
            //         this.setData({
            //             bedside: 0
            //         })
            //         break
            // }
            // }
        }

    },
    nextStage: function () {
        this.setData({
            stage: 2
        })
        this.loading()
    },
    stage3: function () {
        this.setData({
            stage: 3
        })
    },
    cancel: function () {
        wx.switchTab({
            url: '/pages/index/index',
        })
    },
    loading: async function () {
        app.globalData.bluetoothInfo = null
        app.globalData.bluetoothInfo2 = null
        const _this = this
        let bedinfo = this.data.bedinfo
        console.log('bedinfo', this.data.bedinfo)
        console.log('bedside', this.data.bedside)
        let progress = setInterval(() => {
            if (_this.data.value < 80) {
                _this.setData({
                    value: _this.data.value + 20
                })
            } else {
                clearInterval(progress)
            }
        }, 1000);
        console.log('failedFlag=====>', this.data.failedFlag)
        if (this.data.failedFlag == false) { //正常连接
            if (this.data.bedside == 1) {
                //左侧
                await bluetoothUtils.oneTouchConnectBluetooth(bedinfo.left_device_id)
                if (app.globalData.bluetooth_connected == false) {
                    this.stage3()
                    return
                }

            } else if (this.data.bedside == 0) {
                //右侧
                await bluetoothUtils.oneTouchConnectBluetooth(bedinfo.right_device_id)
                if (app.globalData.bluetooth_connected == false) {
                    this.stage3()
                    return
                }
            } else {
                //一人睡双床
                await bluetoothUtils.oneTouchConnectBluetooth(bedinfo.left_device_id)
                if (app.globalData.bluetooth_connected == false) {
                    this.stage3()
                    return
                }
                await bluetoothUtils.oneTouchConnectBluetooth(bedinfo.right_device_id)
                console.log('connect2=====>', app.globalData.bluetooth_connected2)
                if (app.globalData.bluetooth_connected2 == false) {
                    this.stage3()
                    return
                }
            }
            if (this.data.bedside == 0) {
                app.globalData.deviceId = this.data.bedinfo.right_device_id
            } else if (this.data.bedside == 1) {
                app.globalData.deviceId = this.data.bedinfo.left_device_id
            } else {
                app.globalData.deviceId = this.data.bedinfo.left_device_id
                app.globalData.deviceId2 = this.data.bedinfo.right_device_id
            }
            let data = {
                qrcode: this.data.bedinfo.qrcode,
                bed_side: this.data.bedside
            }
            console.log('info=====>', data)
            app.globalData.bedside = this.data.bedside
            console.log('bedside', this.data.bedside)
            api.bind(data, app.globalData.token).then(async function (res) {
                if (res.data.code == 200) {
                    console.log(res)
                    _this.setData({
                        value: 100,
                        hasbind: true
                    })
                    let data = {
                        qrcode: _this.data.bedinfo.qrcode
                    }
                    await api.bedSide(data, app.globalData.token).then(async function (res) {
                        if (res.data.code == 200) {
                            let bedmsg = res.data.data
                            app.globalData.bedInfo[0] = bedmsg.left_device_id
                            app.globalData.bedInfo[1] = bedmsg.right_device_id
                            app.globalData.stateInfo[0] = bedmsg.left_online_flag
                            app.globalData.stateInfo[1] = bedmsg.right_online_flag
                        } else {
                            console.log('Error====>', res.data.msg)
                            bluetoothUtils.myShowToast(res.data.msg)
                            if (app.globalData.bluetoothInfo) {
                                app.globalData.bluetooth_connected = false
                                bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo.deviceID)
                            }
                            if (app.globalData.bluetoothInfo2) {
                                app.globalData.bluetooth_connected2 = false
                                bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo2.deviceID)
                            }
                            _this.stage3()
                        }
                    })
                    setTimeout(() => {
                        wx.switchTab({
                            url: '/pages/index/index',
                        })
                    }, 200)
                } else {
                    console.log('Error====>', res.data.msg)
                    bluetoothUtils.myShowToast(res.data.msg)
                    if (app.globalData.bluetoothInfo) {
                        app.globalData.bluetooth_connected = false
                        bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo.deviceID)
                    }
                    if (app.globalData.bluetoothInfo2) {
                        app.globalData.bluetooth_connected2 = false
                        bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo2.deviceID)
                    }
                    _this.stage3()
                }
            })
        } else { //失败后重连
            let code = 0
            if (app.globalData.failDevice == app.globalData.deviceId) {
                code = await bluetoothUtils.oneTouchConnectBluetooth(app.globalData.deviceId)
                if (code == 100) {
                    if (app.globalData.deviceId2 != null) {
                        let code2 = await bluetoothUtils.oneTouchConnectBluetooth(app.globalData.deviceId2)
                        await bluetoothUtils.errorHandle(code, true)
                        if (code2 == 100) {
                            this.setData({
                                value: 100,
                                failedFlag: false,
                                hasbind: true
                            })
                            wx.switchTab({
                                url: '/pages/index/index',
                            })

                        } else {
                            this.stage3()
                            return
                        }
                    } else {
                        this.setData({
                            value: 100,
                            failedFlag: false,
                            hasbind: true
                        })
                        wx.switchTab({
                            url: '/pages/index/index',
                        })
                    }
                } else {
                    this.stage3()
                    return
                }
            } else if (app.globalData.failDevice == app.globalData.deviceId2) {
                code = await bluetoothUtils.oneTouchConnectBluetooth(app.globalData.deviceId2)
                if (code == 100) {
                    this.setData({
                        value: 100,
                        failedFlag: false,
                        hasbind: true
                    })
                    wx.switchTab({
                        url: '/pages/index/index',
                    })
                } else {
                    this.stage3()
                    return
                }
            } else if (app.globalData.failDevice2 == app.globalData.deviceId2) {
                code = await bluetoothUtils.oneTouchConnectBluetooth(app.globalData.deviceId2)
                if (code == 100) {
                    this.setData({
                        value: 100,
                        failedFlag: false,
                        hasbind: true
                    })
                    wx.switchTab({
                        url: '/pages/index/index',
                    })
                } else {
                    this.stage3()
                    return
                }
            } else {
                this.stage3()
                return
            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('options', options)
        if (options.stage) {
            if (options.stage == 3) {
                this.stage3()
                this.setData({
                    failedFlag: true
                })
                return
            }
        }
        this.data.bedinfo = JSON.parse(options.obj)
        console.log('bedinfo', this.data.bedinfo)
        let params = JSON.parse(options.obj)
        this.bedsituation(params)
        if (options.reconnect) {
            console.log('bedsidetest======>', app.globalData.bedside)
            this.setData({
                stage: 2,
                bedside: app.globalData.bedside
            })
            this.loading()
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        if (this.data.failedFlag == true) {
            app.globalData.failDevice = app.globalData.deviceId
            app.globalData.deviceId = null
            app.globalData.deviceId2 = null
            app.globalData.bluetoothInfo = null
            app.globalData.bluetoothInfo2 = null
        }
        if (this.data.hasbind == false) {
            app.globalData.failDevice = app.globalData.deviceId
            app.globalData.deviceId = null
            app.globalData.deviceId2 = null
            if (app.globalData.bluetoothInfo) {
                app.globalData.bluetooth_connected = false
                bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo.deviceID)
            }
            if (app.globalData.bluetoothInfo2) {
                app.globalData.bluetooth_connected2 = false
                bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo2.deviceID)
            }
            setTimeout(() => {
                app.globalData.bluetoothInfo = null
                app.globalData.bluetoothInfo2 = null
            }, 1500)
        }
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        if (this.data.failedFlag == true) {
            app.globalData.deviceId = null
            app.globalData.deviceId2 = null
            app.globalData.bluetoothInfo = null
            app.globalData.bluetoothInfo2 = null
        }
        if (this.data.hasbind == false) {
            app.globalData.deviceId = null
            app.globalData.deviceId2 = null
            if (app.globalData.bluetoothInfo) {
                app.globalData.bluetooth_connected = false
                bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo.deviceID)
            }
            if (app.globalData.bluetoothInfo2) {
                app.globalData.bluetooth_connected2 = false
                bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo2.deviceID)
            }
            setTimeout(() => {
                app.globalData.bluetoothInfo = null
                app.globalData.bluetoothInfo2 = null
            }, 1500)
        }
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})